<template>
  <el-date-picker style="width: 100%"
    v-if="auth === 'edit'"
    :class="wrapperClass"
    v-model="model"
    :placeholder="placeholder"
    :type="field.dateType"
    :value-format="field.dateFormat"
    :format="field.dateFormat"
    @change="fieldValueChange"
  />

  <el-text truncated v-else-if="auth === 'browse'">
    {{ model }}
  </el-text>

  <el-input v-else-if="auth === 'hide'" v-model="model" disabled
            type="password" @blur="fieldValueChange"/>

  <el-text truncated v-else-if="auth === 'static'">
    {{ model }}
  </el-text>
</template>
<script setup>
import {computed, defineProps, ref, unref} from 'vue';
import {DefaultFieldDefinition} from '@/components/form/DefaultFormDefinition';
import {isEmpty} from '@/utils/CommonUtils';
import './textInput.css';

const props = defineProps({
  auth: {
    type: String,
    default: 'static'
  },
  notNull: {
    type: String,
    default: '0' //0表示非必填, 1表示必填
  },
  field: {
    type: Object,
    default() {
      return DefaultFieldDefinition;
    }
  }
});
const model = ref();
const emits = defineEmits(['fieldValueChange']);

function getFieldValue(rowData) {
  return unref(model);
}

function resetField() {
  model.value = undefined;
}

function setFieldValue(value, obj) {
  model.value = value;
}

function fieldValueChange() {
  emits('fieldValueChange', props.field);
}

function getFieldValueText() {
  return unref(model);
}

function getFieldValueWithCheck(rowData) {
  if (props.notNull + '' === '1' && isEmpty(model.value)) {
    throw new Error('请将必填项填写完整');
  }
  return model.value;
}

const placeholder = computed(() => {
  if (isEmpty(props.field.id)) return '';
  return `请输入${props.field.alias ? props.field.alias : props.field.showName}`;
});

const wrapperClass = computed(() => {
  return {
    notNull: props.notNull === '1' && isEmpty(model.value)
  };
});

defineExpose({
  getFieldValue,
  setFieldValue,
  resetField,
  getFieldValueText,
  getFieldValueWithCheck,
});
</script>
